package com.example.testapp.activity.activity.menu;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Display;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.example.testapp.R;
import com.example.testapp.activity.adapter.CalendarAdapter;
import com.example.testapp.activity.dabastate.CalendarDao;
import com.example.testapp.activity.view.TitleTextView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created by l on 2016/5/9.
 */
public class DateActivity extends Activity implements GestureDetector.OnGestureListener {

    private GestureDetector mGestureDetector = null;
    private ViewFlipper  flipper = null;

    private GridView gridView = null;
    private CalendarAdapter  mAdapter = null;
    private TitleTextView topText = null;
    private Drawable  draw = null;

    private static int jumpMonth = 0;
    private static int jumpYear = 0;
    private int year_c = 0;
    private int month_c = 0;
    private int day_c = 0;
    private String currentDate = " ";

    private CalendarDao dao = null;

    public DateActivity(){
        Date  date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
        currentDate = sdf.format(date); //当期日期
        year_c = Integer.parseInt(currentDate.split("-")[0]);
        month_c = Integer.parseInt(currentDate.split("-")[1]);
        day_c = Integer.parseInt(currentDate.split("-")[2]);

        dao = new CalendarDao(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_date);
        Toolbar toolbar = (Toolbar)findViewById(R.id.date_toolbar);
        toolbar.setLogo(R.mipmap.ic_launcher);
        toolbar.setTitle(R.string.action_date);
        toolbar.setTitleTextColor(Color.WHITE);
        toolbar.inflateMenu(R.menu.menu_date);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int menuItemId = item.getItemId();
                if(menuItemId == R.id.today){
                    //Toast.makeText(DateActivity.this , "1" , Toast.LENGTH_SHORT).show();
                    ToDayTextView();
                }else if(menuItemId == R.id.tiao_zhuan){
                    //Toast.makeText(DateActivity.this , "2" , Toast.LENGTH_SHORT).show();
                    TiaoZhuanTextView();
                }else if(menuItemId == R.id.ri_cheng){
                    //Toast.makeText(DateActivity.this , "3" , Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(DateActivity.this, CalendarAllActivity.class));
                }else if(menuItemId == R.id.date_huan){
                    //Toast.makeText(DateActivity.this , "4" , Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent();
                    intent.setClass(DateActivity.this, CalendarConvertActivity.class);
                    intent.putExtra("date", new int[]{year_c, month_c, day_c});
                    startActivity(intent);
                }
                return true;
            }
        });

        mGestureDetector = new GestureDetector(this);
        flipper = (ViewFlipper) findViewById(R.id.flipper);
        flipper.removeAllViews();

        mAdapter = new CalendarAdapter(this, getResources(), jumpMonth, jumpYear, year_c, month_c, day_c);

        addGridView();
        gridView.setAdapter(mAdapter);
        flipper.addView(gridView, 0);

        topText = (TitleTextView)findViewById(R.id.toptext);
        addTextToTopTextView(topText);
    }

    private void ToDayTextView() {
        int xMonth = jumpMonth;
        int xYear = jumpYear;
        int gvFlag = 0;
        jumpMonth = 0;
        jumpYear = 0;
        addGridView();
        year_c = Integer.parseInt(currentDate.split("-")[0]);
        month_c = Integer.parseInt(currentDate.split("-")[1]);
        day_c = Integer.parseInt(currentDate.split("-")[2]);
        mAdapter = new CalendarAdapter(this, getResources(), jumpMonth,jumpYear,year_c, month_c, day_c);
        gridView.setAdapter(mAdapter);
        addTextToTopTextView(topText);
        gvFlag++;
        flipper.addView(gridView, gvFlag);
        if(xMonth == 0 && xYear == 0){

        }else if((xYear == 0 && xMonth > 0) || xYear > 0){
            this.flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_in));
            this.flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_out));
            this.flipper.showNext();
        }else {
            this.flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_in));
            this.flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_out));
            this.flipper.showPrevious();
        }
        flipper.removeViewAt(0);
    }

    private void TiaoZhuanTextView() {
         new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
             @Override
             public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                  if(year < 1901 || year > 2049){
                      Toast.makeText(DateActivity.this, "跳转范围1901/1/1-2049/12/31", Toast.LENGTH_SHORT).show();
                  }else{
                      int gvFlag = 0;
                      addGridView();
                      mAdapter = new CalendarAdapter(DateActivity.this, getResources(), year, monthOfYear+1, dayOfMonth);
                      gridView.setAdapter(mAdapter);
                      addTextToTopTextView(topText);
                      gvFlag++;
                      flipper.addView(gridView, gvFlag);
                      if(year == year_c && monthOfYear + 1 == month_c){

                      }
                      if((year == year_c && monthOfYear + 1 > month_c) || year > year_c){
                          flipper.setInAnimation(AnimationUtils.loadAnimation(DateActivity.this, R.anim.push_left_in));
                          flipper.setInAnimation(AnimationUtils.loadAnimation(DateActivity.this, R.anim.push_left_out));
                          flipper.showNext();
                      }else{
                          flipper.setInAnimation(AnimationUtils.loadAnimation(DateActivity.this, R.anim.push_right_in));
                          flipper.setInAnimation(AnimationUtils.loadAnimation(DateActivity.this, R.anim.push_right_out));
                          flipper.showPrevious();
                      }
                      flipper.removeViewAt(0);
                      //跳转之后将跳转之后的日期设置为当期日期
                      year_c = year;
                      month_c = monthOfYear + 1;
                      day_c = dayOfMonth;
                      jumpMonth = 0;
                      jumpYear = 0;
                  }
             }
         }, year_c, month_c-1, day_c).show();
    }

    private void addGridView() {
        final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        //取得屏幕的宽度和高度
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();

        gridView = new GridView(this);
        gridView.setNumColumns(7);
        gridView.setColumnWidth(46);

        if(width == 480 && height == 800){
            gridView.setColumnWidth(69);
        }
        gridView.setGravity(Gravity.CENTER_VERTICAL);
        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gridView.setVerticalSpacing(1);
        gridView.setHorizontalSpacing(1);
        gridView.setBackgroundResource(R.mipmap.gridview_bk);
        gridView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return DateActivity.this.mGestureDetector.onTouchEvent(event);
            }
        });
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //点击任何一个item，得到这个item的日期(排除点击的是周日到周六(点击不响应))
                int startPosition = mAdapter.getStartPosition();
                int endPosition = mAdapter.getEndPosition();
                if(startPosition <= position && position <= endPosition){
                    String scheduleDay = mAdapter.getDateByClickItem(position).split("\\.")[0]; //这一天的阳历
                    String schedultYear = mAdapter.getShowYear();
                    String schedultMonth = mAdapter.getShowMonth();
                    String week = " ";

                    //通过日期查询这一天是否被标记，如果标记了日程就查询出这天的所有日程信息
                    String[] scheduleIDs = dao.getScheduleByTagDate(Integer.parseInt(schedultYear), Integer.parseInt(schedultMonth), Integer.parseInt(scheduleDay));
                    if(scheduleIDs != null && scheduleIDs.length > 0){
                        //跳转到显示这一天的所有日程信息界面
                        Intent intent = new Intent();
                        intent.setClass(DateActivity.this, CalendarInfoViewActivity.class);
                        intent.putExtra("scheduleID", scheduleIDs);
                        startActivity(intent);
                    }else{
                        //直接跳转到需要添加日程的界面

                        //得到这一天是星期几
                        switch (position%7){
                            case 0:
                                week = "星期日";
                                break;
                            case 1:
                                week = "星期一";
                                break;
                            case 2:
                                week = "星期二";
                                break;
                            case 3:
                                week = "星期三";
                                break;
                            case 4:
                                week = "星期四";
                                break;
                            case 5:
                                week = "星期五";
                                break;
                            case 6:
                                week = "星期六";
                                break;
                        }
                        ArrayList<String> scheduleDate = new ArrayList<String>();
                        scheduleDate.add(schedultYear);
                        scheduleDate.add(schedultMonth);
                        scheduleDate.add(scheduleDay);
                        scheduleDate.add(week);

                        Intent intent = new Intent();
                        intent.putStringArrayListExtra("scheduleDate", scheduleDate);
                        intent.setClass(DateActivity.this, CalendarViewActivity.class);
                        startActivity(intent);
                    }
                }
            }
        });
         gridView.setLayoutParams(params);
    }

    //添加头部的年份 闰哪月等信息
    private void addTextToTopTextView(TextView view) {
        StringBuffer textDate = new StringBuffer();
        draw = getResources().getDrawable(R.mipmap.top_day);
        view.setBackgroundDrawable(draw);
        textDate.append(mAdapter.getShowYear()).append("年").append(
                mAdapter.getShowMonth()).append("月").append("\t");
        if (!mAdapter.getLeapMonth().equals("") && mAdapter.getLeapMonth() != null) {
            textDate.append("闰").append(mAdapter.getLeapMonth()).append("月").append("\t");
        }
        /*textDate.append(mAdapter.getAnimalsYear()).append("年").append("(").append(
                mAdapter.getCyclical()).append("年)");*/
        view.setText(textDate);
        view.setTextColor(Color.BLACK);
        view.setTypeface(Typeface.DEFAULT_BOLD);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        int gvFlag = 0;
        if(e1.getX() - e2.getX() > 120){
            //像左滑动
            addGridView();   //添加一个gridView
            jumpMonth++;     //下一个月

            mAdapter = new CalendarAdapter(this, getResources(), jumpMonth, jumpYear, year_c, month_c, day_c);
            gridView.setAdapter(mAdapter);

            addTextToTopTextView(topText);
            gvFlag++;

            flipper.addView(gridView, gvFlag);
            this.flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_in));
            this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_out));
            this.flipper.showNext();
            flipper.removeViewAt(0);
        }else if(e1.getX() - e2.getX() < -120){
            //向右滑动
            addGridView();   //添加一个gridView
            jumpMonth--;     //上一个月

            mAdapter = new CalendarAdapter(this, getResources(), jumpMonth, jumpYear, year_c, month_c, day_c);
            gridView.setAdapter(mAdapter);
            gvFlag++;
            addTextToTopTextView(topText);

            flipper.addView(gridView, gvFlag);
            this.flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_in));
            this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_out));
            this.flipper.showPrevious();
            flipper.removeViewAt(0);
            return true;
        }
        return false;
    }
}
